package cn.gok.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.gok.entity.Exc;
import cn.gok.service.ExcService;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/api/exc")
public class ExcController {
    @Autowired
    private ExcService excService;

    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Exc> excels=excService.findAll();
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("漏洞列表信息","漏洞信息"),Exc.class,excels);
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("漏洞列表.xls","UTF-8"));
        ServletOutputStream outputStream=response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

    @RequestMapping("/import")
    public String importExcel(MultipartFile excelFile) throws Exception {
        ImportParams params=new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Exc> excels= ExcelImportUtil.importExcel(excelFile.getInputStream(),Exc.class,params);
        excService.update(excels);
//        userService.saveAll(users);
        return "redirect:http://localhost:8081/#/loophole";
    }

    @ResponseBody
    @RequestMapping("/findAll")
    public JSONObject findAll(@RequestBody JSONObject json){
        List<Exc> excels=excService.findAll();
        JSONObject res=new JSONObject();
        res.put("data",excels);
        return  res;
    }
}
